(function (window, $, undefined) {
  'use strict';

  var dictData = {
    businessType: [
      '立即用车',
      '预约用车',
      '预约接机/站',
      '预约送机/站',
      '立即接机/站',
      '立即送机/站',
      '预约接送机/站',
      '立即接送机/站'
    ],
    carType: [
      '舒适型',
      '商务7座',
      '豪华轿车'
    ],
    availableCity: [

    ],
    offerType: [
      '常规价',
      '一口价',
      '套餐价'
    ],
    userChannel: [
      '小程序专用',
      'APP专用'
    ],
    userType: [
      '本人使用',
      '替他人叫车使用'
    ],
    status: {
      '0': '已使用',
      '1': '未使用'
    }
  };

  var couponData = {};

  main(function () {

    var $tableCoupon = $('#table-coupon');

    util.jqGrid($tableCoupon, {
      url: ajaxURL.COUPON + '/coupon/v1/userCoupon/queryWithPage',
      // datatype: 'json',
      mtype: 'POST',
      autowidth: true,
      height: $(window).height() - 320,
      multiselect: true,
      multiboxonly: true,
      shrinkToFit: false,
      colModel: [
        { label: '编号', key: true, name: 'couponCode', width: 120 },
        {
          label: '使用渠道', name: 'userChannels', width: 100, formatter: function (v, o, r) {
            var curValues = dictData.userChannel;
            var len = curValues.length;
            var val = (+v).toString(2).split('');
            var ret = [];
            var vLen = val.length;
            if (vLen === len && Math.pow(2, len) - 1 === v) {
              return '通用';
            }

            for (var i = 0; i < vLen; i++) {
              if (val[i] === '1') {
                ret.push(curValues[i + len - vLen]);
              }
            }

            return ret.join('、');
          }
        },
        {
          label: '地域范围', name: 'availableCitys', width: 100, formatter: function (v, o, r) {
            var curValues = dictData.availableCity;
            var len = curValues.length;
            var val = (+v).toString(2).split('').reverse();
            var ret = [];
            var vLen = val.length;
            if (vLen === len && Math.pow(2, len) - 1 === v) {
              return '通用';
            }

            for (var i = 0; i < vLen; i++) {
              if (val[i] === '1') {
                ret.push(curValues[i + len - vLen]);
              }
            }

            return ret.join('、');
          }
        },
        {
          label: '服务类型', name: 'businessTypes', width: 100, formatter: function (v, o, r) {
            var curValues = dictData.businessType;
            var len = curValues.length;
            var val = (+v).toString(2).split('');
            var ret = [];
            var vLen = val.length;
            if (vLen === len && Math.pow(2, len) - 1 === v) {
              return '通用';
            }

            for (var i = 0; i < vLen; i++) {
              if (val[i] === '1') {
                ret.push(curValues[i + len - vLen]);
              }
            }

            return ret.join('、');
          }
        },
        {
          label: '面额(元)', name: 'couponAmount', width: 100 },
        { label: '是否支持折后使用', name: 'discountFlag', width: 120, formatter: function (v, o, r) {
          return ['', '是', '否'][v] || '';
        } },
        { label: '是否领用', name: 'isGet', width: 80, formatter: function (v, o, r) {
          return ['', '是', '否'][v] || '';
        } },
        { label: '用户电话', name: 'phone', width: 100 },
        {
          label: '是否使用', name: 'status', width: 80, formatter: function (v, o, r) {
            return ['', '已使用', '未使用'][v] || '';
          }
        },
        {
          label: '有效期', name: 'useTime', width: 180, formatter: function (v, o, r) {
            var now = util.getTime(util.getDate(true) + ' 00:00:00');
            var ret = util.getDate(r.useStartTime) + ' 至 ' + util.getDate(r.useEndTime);
            // var ret = util.dateFormat(r.useEndTime);
            if (now > r.useEndTime) {
              ret += ' (<span class="text-danger">已过期</span>)';
            }
            return ret;
          }
        },
        { name: 'useEndTime', hidden: true },
        { name: 'useStartTime', hidden: true }
      ],
      loadComplete: function (res) {
        couponData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            couponData[item.couponCode] = item;
          });
        }
      },
      pager: '#pager-coupon'
    });

    // 获取城市列表
    util.get(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', function (res) {
      $.each(res.data, function (_, item) {
        dictData.availableCity.push(item.name);
      });

      renderSelect();

      searchTable();
      $('#btn-search').click(searchTable);
    });

    function renderSelect() {
      ['availableCity', 'userChannel', 'businessType'].forEach(function (name) {
        var $elem = $('select[name="' + name + '"]');
        var curData = dictData[name];
        var len = curData.length;
        var allValue = 0;
        var ret = '';
        $.each(curData, function (_, item) {
          var p = name === 'availableCity' ? _ : len - _ - 1;
          var v = Math.pow(10, p);
          allValue += v;
          ret += '<option value="' + v + '">' + item + '</option>';
        });
        ret = '<option value="' + allValue + '">全部</option>' + ret;
        $elem.html(ret).val(allValue);
      });
    }

    util.selectHtml($('[name="status"]'), dictData.status, '', '', '请选择');

    // 搜索
    function searchTable() {
      var data = util.formData('#form-search');
      if (data.couponDate) {
        data.date = util.getTime(data.date);
      }

      util.searchGrid($tableCoupon, data);
    }

    $('#btn-search').click(searchTable);

    // 有效期
    laydate.render({
      range: '至',
      elem: '#coupon-date',
      type: 'datetime',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#coupon-date').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 查看优惠券
    $('#btn-detail').click(util.oneCheck($tableCoupon, function (id, data) {

      // console.log(arguments);

    }));




  });


})(window, jQuery);
